package com.westa.smallshop.util.volley;

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;

/**
 * Created by dune on 15/12/14.
 */

public class VolleySingleton {

    private static VolleySingleton ourInstance;
    private RequestQueue requestQueue;


    private static final DefaultRetryPolicy defaultRetryPolicy = new DefaultRetryPolicy(5000, 0, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);


    private VolleySingleton(Context context) {
        requestQueue = Volley.newRequestQueue(context, new OkHttpStack());
    }

    public static VolleySingleton createInstance(Context context) {
        if (context != null) {
            if (ourInstance == null) {
                ourInstance = new VolleySingleton(context);
            }
        } else {
            throw new IllegalArgumentException("Context must be set");
        }
        return ourInstance;
    }

    public static RequestQueue getRequestQueue() {
        return ourInstance.requestQueue;
    }

    public static void addRequest(Request request, String tag) {

        request.setTag(tag);
        request.setRetryPolicy(defaultRetryPolicy);
        getRequestQueue().add(request);
    }

    public static void cancelRequestForStartWithTag(final String tag) {

        getRequestQueue().cancelAll(new RequestQueue.RequestFilter() {
            @Override
            public boolean apply(Request<?> request) {

                String t = (String) request.getTag();
                return t != null && t.startsWith(tag);
            }
        });
    }
}

